﻿using System.IO;
using System.Threading.Tasks;

namespace LeoGemini.Service.Infrastructure.Extension
{
    public static partial class Extensions
    {
        private const int BUFFER_SIZE = 84975;
        public static async Task<long> WriteToPathAsync(this Stream stream, string path)
        {
            long writeCount = 0;
            
            using (FileStream st = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write, BUFFER_SIZE, true))
            {
                byte[] bytes = new byte[BUFFER_SIZE];
                int readCount = 0;
                // 读取文件流并写进bytes缓冲池
                while ((readCount = await stream.ReadAsync(bytes, 0, BUFFER_SIZE)) > 0)
                {
                    // 写出缓冲区数据
                    await st.WriteAsync(bytes, 0, readCount);
                    writeCount += readCount;
                }
            }
            
            return writeCount;
        }
    }
}